module XvgRoutine

# using GR
using DataFrames
using XvgParser
using Utils

function xvg_functions(xvg::XVG, xvgfilename::String)
    # TODO: 添加画图功能
    # TODO: 添加x-label, y-label和title
    while true
        println(h("\n                    ************ XVG functions ************", fc="c"))
        println("-3 Toggle: converting table format (tall/wide), current: " * (xvg.istall ? "tall" : "wide"))
        println("-2 Preview XVG data in fig")
        println("-1 Show XVG data")
        println(" 0 Return to main menu")
        println(" 1 Output to .csv data file")
        println(" 2 Adjust XVG data")
        println(" 3 Append another XVG")
        input = sel_fun(Int32)
        if input == -3
            println("\nConverting, please wait...")
            XvgParser.toggle_tall_wide!(xvg)
            finish_hint("Convertion finished.\n")
        elseif input == -2
            # TODO: 看能不能把格式语法兼容性的问题解决一下, e.g., Chain_Separator
            # if xvg.istall
            #     println("\n$(h("NOTE: ", fc="y"))Here data will be automatically adjusted to wide mode.")
            #     XvgParser.toggle_tall_wide!(xvg)
            # end
            # df = xvg.xvgdata
            # x = df[!, xvg._xlabel]
            # y = Matrix(df[!, xvg._legends])
            # legend(xvg._legends...)
            # xlabel(xvg._xlabel)
            # ylabel(xvg._ylabel)
            # title(xvg._title)
            # plot(x, y, linewidth=2)
            # request_hint("\nPlotted xvg data. Save it? [y/N]")
            # if get_input("n") != "n"
            #     request_hint("Select fig extension:\n")
            #     println(" 0 png")
            #     println(" 1 svg")
            #     println(" 2 pdf")
            #     ext = sel_fun(Int32)
            #     try
            #         ext = Dict{Int32, String}(0 => "png", 1 => "svg", 2 => "pdf")[ext]
            #     catch
            #         error("Error input.")
            #     end
            #     savefig(get_path(xvgfilename, false, ext))
            #     finish_hint("Finished saving fig.\n")
            # end
        elseif input == -1
            title_hint("\nContents of " * xvg._title * "\n")
            println(xvg.xvgdata)
        elseif input == 0
            return
        elseif input == 1
            path = get_path(xvgfilename, false, "csv")
            xvg2csv(xvg, path)
            finish_path(path)
        elseif input == 2
            initxvg = deepcopy(xvg)
            while true
                println(p("\nAdjust XVG data:", fc="c"))
                println("-10 Revert to initial")
                println(" 0 Return")
                println(" 1 Shift x axis by a value")
                println(" 2 Multiply x axis by a value")
                println(" 3 Multiply y axis by a value")
                println(" 4 Extract x values at specified interval")
                println(" 5 Convert x values from unit ps to ns")
                input = sel_fun(Int32)
                if input == 0
                    break
                elseif input == -10
                    xvg = initxvg
                    finish_hint("Reverted to initial xvg.\n")
                elseif input == 1
                    request_hint("\nInput shift value (default: 0): ")
                    shift_value = get_input(0, Float64)
                    xvg.xvgdata[!, xvg._xlabel] .+= shift_value
                    finish_hint("\nFinished adjusting.\n")
                elseif input == 2
                    request_hint("\nInput multiple value (default: 1): ")
                    shift_value = get_input(1, Float64)
                    xvg.xvgdata[!, xvg._xlabel] .*= shift_value
                    finish_hint("\nFinished adjusting.\n")
                elseif input == 3
                    request_hint("\nInput multiple value (default: 1): ")
                    shift_value = get_input(1, Float64)
                    xvg.xvgdata[!, 2:end] .*= shift_value
                    finish_hint("\nFinished adjusting.\n")
                elseif input == 4
                    if xvg.istall
                        println("\n$(h("NOTE: ", fc="y"))Here data will be automatically adjusted to wide mode.")
                        XvgParser.toggle_tall_wide!(xvg)
                    end
                    request_hint("Input which rows to extract: (default: select all rows)\n")
                    println("You can directly input or use syntax $(h("begin:step_length:end", fc="y")).")
                    println("\nFor example, if x=[1, 2, 3, 4, 5, 6, 7, 8, 9], then")
                    println("1 2 3 6 7\t▶\t1 2 3 6 7")
                    println("1:2:7\t\t▶\t1 3 5 7 9")
                    println("1:3:7\t\t▶\t1 4 7")
                    println("begin:4:end\t▶\t1 5 9")
                    println("begin:end\t▶\t1 2 3 4 5 6 7 8 9")
                    r = get_input("begin:end")
                    try
                        if occursin(":", r)     # 1:2:5
                            r = replace(r, "begin" => "1", "end" => size(xvg.xvgdata, 1))
                        else                    # 1 2 5
                            r = "[$(join(split(r), ","))]"
                        end
                        xvg.xvgdata = xvg.xvgdata[eval(Meta.parse(r)), :]
                        finish_hint("\nFinished extracting.\n")
                    catch
                        error_hint("Error: input not valid.")
                    end
                elseif input == 5
                    if xvg._xlabel == "Time (ps)"
                        xvg.xvgdata[!, xvg._xlabel] *= 0.001
                        rename!(xvg.xvgdata, "Time (ps)" => "Time (ns)")
                        xvg._xlabel = "Time (ns)"
                        finish_hint("\nFinished adjusting.\n")
                    else
                        error_hint("Error: x axis is $(xvg._xlabel), not Time (ps).\n")
                    end
                end
            end
        elseif input == 3
            request_hint("Input path(s) of another xvg file, one per line or leave blank to stop:\n")
            xvg_list = Vector{AbstractString}()
            while true
                new_xvg = prev_local2abs(get_input(""), xvgfilename)
                if isempty(new_xvg)
                    break
                end
                if check_file(new_xvg)
                    push!(xvg_list, new_xvg)
                else
                    continue
                end
            end
            println("Appending xvg(s), please wait...")
            for new_xvg in xvg_list
                XvgParser.append_xvg!(xvg, new_xvg)
            end
            finish_hint("Finished appending xvg(s).\n")
        end
    end
end

end